import React, { useState } from 'react';
import { Collapse } from 'antd';
import styled from '@emotion/styled';
import MessageItem from './MessageItem';
import VideoPreview from './preview/VideoPreview';
import PdfPreview from './preview/PdfPreview';
import { getFileTypeFromText } from '../../utils/index';
import { SendOutlined } from '@ant-design/icons';

const { Panel } = Collapse;

export interface IMessage {
	id: string;
	from: string;
	type?: string;
	text: string;
	fileName?: string;
	ratingType?: string;
	question?: string;
	questions?: string[];
	noanswer?: boolean;
}

interface MessageListProps {
	messageList: IMessage[];
	onSelect?: (question: string) => void;
	onSend: (message: IMessage) => void;
}



const MessageList: React.FC<MessageListProps> = props => {
	const { messageList = [], onSelect, onSend } = props;
	const [curVideoUrl, setCurVideoUrl] = useState<string | null>(null);
	const [curPdfUrl, setCurPdfUrl] = useState<string | null>(null);
	const [curText, setCurText] = useState<string | null>(null);

	const handleSelect = (question: string) => {
		// Perform actions on select
		onSelect && onSelect(question);
	};

	const handlePreview = (message: IMessage) => {
		const type = message.type || getFileTypeFromText(message.text); // Assuming getFileTypeFromText is imported
		if (type === 'image') {
			// Perform actions on image preview
		} else if (type === 'video') {
			setCurVideoUrl(message.text);
		} else if (type === 'pdf') {
			setCurPdfUrl(message.text);
		} else {
			setCurText(message.text);
		}
	};

	const handleSend = (message: IMessage) => {
		console.log('handleSend ', message);
		onSend(message);
	};

	const genExtra = (message: IMessage) => (
		<SendOutlined
			onClick={event => {
				// If you don't want click extra trigger collapse, you can prevent this:
				event.stopPropagation();
				handleSend(message);
			}}
		/>
	);

	return (
		<Container>
			{messageList.length > 0 && (
				<Collapse defaultActiveKey={['1']}>
					{messageList.map((item, index) => {
						if (item.noanswer) {
							return <NoAnswerMessageItem>{item.text}</NoAnswerMessageItem>;
						} else {
							return (
								<Panel header={item.question} key={`${item.id}_${index}`} extra={genExtra(item)}>
									<MessageItem message={item} onSelect={handleSelect} onPreview={handlePreview} />
								</Panel>
							);
						}
					})}
				</Collapse>
			)}
			{curVideoUrl && <VideoPreview videoUrl={curVideoUrl} onClose={() => setCurVideoUrl(null)} />}
			{curPdfUrl && <PdfPreview pdfUrl={curPdfUrl} onClose={() => setCurPdfUrl(null)} />}
		</Container>
	);
};

export default MessageList;

const Container = styled.div`
	overflow-y: auto;
	height: 400px;
`;

const NoAnswerMessageItem = styled.p`
	line-height: 50px;
    padding: 0 10px;
    border-bottom: 1px solid #d9d9d9;
`;
